<template>
  <div id="bugmask">
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="400"
    >
      <template #header>
        <div class="my-header">
          <div class="header-title mb20">
            <button
              style=""
              @click="handleClose"
              class="close-icon curpoin"
              @mouseover="isRotated = true"
              @mouseleave="isRotated = false"
            >
              <!-- src="../../assets/images/close.png" -->
              <img
                style="width: 30px"
                :class="{
                  'rotate-right': isRotated,
                  'rotate-left': !isRotated,
                }"
                src="../../../../assets/images/close.png"
                alt=""
              />
            </button>
            <div style="margin-top: 40px" v-if="isShow">
              <el-form :model="formLabelAlign" style="max-width: 460px">
                <el-form-item label="订购内容"
                  ><div class="f20" style="font-weight: 800">
                    {{ goodsDetData.name || '-' }}
                  </div></el-form-item
                >
                <el-form-item label="订购对象">
                  <el-input
                    size="large"
                    v-model="formLabelAlign.phone"
                    placeholder="手机号"
                  />
                </el-form-item>
                <el-form-item label="实付金额">
                  <span style="color: var(--color-text)"
                    ><span class="f12">￥</span>
                    <span style="font-size: 30px">{{
                      goodsDetData.realPrice || '-'
                    }}</span></span
                  >
                </el-form-item>
              </el-form>
              <div
                class="df"
                style="justify-content: flex-end; margin-right: 30px"
              >
                <el-checkbox v-model="checked1" size="large" />
                <div class="f14 curr" style="margin-left: 5px">
                  我已阅读并同意<span style="color: var(--color-text)"
                    >《服务条款及免责声明》</span
                  >
                </div>
              </div>

              <el-button
                type="primary"
                style="width: 100%"
                size="large"
                @click="handlNext"
              >
                去支付</el-button
              >
            </div>
            <div v-else>
              <div class="df" style="margin-top: 40px">
                <el-icon size="25" class="curr" @click="isShow = true"
                  ><ArrowLeft
                /></el-icon>
                <div style="margin-left: 20px">选择支付方式</div>
              </div>
              <div
                v-loading="imgLoading"
                style="text-align: center; margin: 40px 0 20px 0"
              >
                <img :src="shareQrImage" alt="" class="qrImage" />
              </div>
              <!-- <div style="text-align: center">打开微信/支付宝扫一扫</div> -->
              <div style="text-align: center">打开微信</div>
            </div>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import { getPcGoodsPay, getOrderStatus } from '@/api/shopServe/shopServe';
import QRCode from 'qrcode';
const props = defineProps({
  goodsDetData: {
    type: Object,
    default: () => {},
  },
});

const imgLoading = ref(true);
const store = useStore();
const isShow = ref(true);
const checked1 = ref(false);
const dialogVisible = ref(false);
const shareQrImage = ref('');
const isRotated = ref(false);
const formLabelAlign = ref({
  phone: store.getters.user.userInfo.phone,
});
const buyData = ref({
  id: '',
  phone: '',
});
const handlNext = () => {
  if (formLabelAlign.value.phone && checked1.value) {
    isShow.value = false;
    fetchPcGoodsPay();
  } else if (!formLabelAlign.value.phone) {
    ElMessage.error('请正确填写手机号后支付');
  } else if (!checked1.value) {
    ElMessage.error('请阅读并同意声明后支付');
  }
};
const fetchPcGoodsPay = () => {
  buyData.value.id = props.goodsDetData.id;
  buyData.value.phone = formLabelAlign.value.phone;
  getPcGoodsPay(buyData.value).then((res) => {
    const order_sn = res.data.data.data.order_sn;
    if (res.data.code == 20000) {
      imgLoading.value = true;
      generateQR(res.data.data.data.code_url).then((res) => {
        console.log('res:', res);
        if (res) {
          imgLoading.value = false;
          shareQrImage.value = res;
          // 开始轮询订单状态
          startPolling(order_sn);
        } else {
          imgLoading.value = false;
        }
      });
    }
  });
};
const isPolling = ref(true); // 用于控制轮询的标志

const startPolling = (order_sn, interval = 2000) => {
  // 轮询方法
  const poll = async () => {
    if (!isPolling.value) return; // 如果停止标志为 false，停止轮询

    try {
      const { data } = await getOrderStatus({ order_sn });
      // 如果满足某个条件，可以停止轮询
      if (data.code == 20000) {
        isPolling.value = false; // 停止轮询
        dialogVisible.value = false;
        isShow.value = true;
        ElMessage.success('订单支付完成');
        return;
      }
    } catch (error) {
      console.log('error:', error);
      // ElMessage.error('订单支付失败');
    }

    // 下一次轮询
    if (isPolling.value) {
      setTimeout(poll, interval); // 继续轮询
    }
  };

  poll(); // 开始轮询
};

const generateQR = async (text) => {
  try {
    const opts = {
      errorCorrectionLevel: 'H',
      type: 'image/png',
      quality: 0.9,
      margin: 1,
    };
    const qrImage = await QRCode.toDataURL(text, opts);
    return qrImage;
  } catch (err) {
    imgLoading.value = false;
    console.error(err);
  }
};
const handleClose = () => {
  isPolling.value = false;
  isShow.value = true;
  dialogVisible.value = false;
};
const handleChangeMask = (isShow) => {
  dialogVisible.value = isShow;
};
// 在组件卸载时停止轮询
onUnmounted(() => {
  isPolling.value = false;
});
defineExpose({
  handleChangeMask,
});
</script>

<style lang="scss" scoped>
#bugmask {
  position: relative; /* 设置父元素为相对定位 */
  .my-header {
  }
  .close-icon {
    position: absolute;
    top: 20px;
    right: 10px;
    background: 0 0;
    border: none;
    outline: 0;
    font-size: 16px;
  }
}
.rotate-right {
  transition: transform 0.6s ease;
  transform: rotate(180deg);
}

.rotate-left {
  transition: transform 0.6s ease;
  transform: rotate(0deg);
}
:deep(.qrImage::after) {
  background: red;
}
</style>
